package LeetCode.month01.day01;

import java.util.Scanner;

public class No42 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine();
        String[] chs = s.split(",");

        int[] a = new int[chs.length];
        for (int i = 0; i < chs.length; i++) {
            a[i] = Integer.parseInt(chs[i]);
        }
        System.out.println(trap(a));
    }


    //https://www.bilibili.com/video/BV1Qg411q7ia/?spm_id_from=333.337.search-card.all.click&vd_source=9ddd0f3f9b376058cc16cda016ccb055
    public static int trap(int[] height) {
//        int right=-1,left=-1,sum=0;
//        int len = height.length;
//        int[] pre_max = new int[len];
//        int[] suf_max = new int[len];
//        pre_max[0]=height[0];
//        suf_max[len-1] = height[len-1];
//        for (int i = 1; i < len; i++) {
//            pre_max[i] = Math.max(pre_max[i-1],height[i]);
//            suf_max[len-i-1] = Math.max(suf_max[len-i],height[len-i-1]);
//        }
//        for (int i = 0; i < len; i++) {
//            sum+=Math.min(pre_max[i],suf_max[i])-height[i];
//        }
//        return sum;
        int len = height.length;
        int pre_max =0,suf_max=0,sum=0,right = len-1,left=0;

        while(left<=right){
            pre_max = Math.max(pre_max,height[left]);
            suf_max = Math.max(suf_max,height[right]);
            if(pre_max>suf_max){
                sum+=suf_max-height[right];
                right--;
            }else{
                sum+=pre_max-height[left];
                left++;
            }
        }
        return sum;
    }
}
